﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataHelper {

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="dataName"></param>
    /// <param name="data"></param>
	public static void SaveData(string dataName, object data) {
        if (data is string) { // 字符串
            PlayerPrefs.SetString(dataName, (string) data);
        } else if (data is float) { // 浮点
            PlayerPrefs.SetFloat(dataName, (float) data);
        } else if (data is int) { // 整型
            PlayerPrefs.SetInt(dataName, (int) data);
        } else { // 其他
            PlayerPrefs.SetString(dataName, JsonHelper.ToJsonString(data));
        }
    }

    /// <summary>
    /// 读取数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataName"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static T LoadData<T>(string dataName, string defaultValue) where T : class {
        string data = PlayerPrefs.GetString(dataName, defaultValue);
        return JsonHelper.ParseObject<T>(data);
    }

    /// <summary>
    /// 读取List类型数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataName"></param>
    /// <returns></returns>
    public static T LoadListData<T>(string dataName) where T : class {
        return LoadData<T>(dataName, "[]");
    }

    /// <summary>
    /// 读取object类型数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataName"></param>
    /// <returns></returns>
    public static T LoadObjectData<T>(string dataName) where T : class {
        return LoadData<T>(dataName, "{}");
    }

    /// <summary>
    /// 读取string类型数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataName"></param>
    /// <returns></returns>
    public static string LoadStringData(string dataName) {
        return PlayerPrefs.GetString(dataName, null);
    }

    /// <summary>
    /// 读取int类型数据
    /// </summary>
    /// <param name="dataName"></param>
    /// <returns></returns>
    public static int LoadIntData(string dataName) {
        return PlayerPrefs.GetInt(dataName, 0);
    }

    /// <summary>
    /// 读取float类型数据
    /// </summary>
    /// <param name="dataName"></param>
    /// <returns></returns>
    public static float LoadFloatData(string dataName) {
        return PlayerPrefs.GetFloat(dataName, 0);
    }
}
